﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zen.Barcode;
using System.Drawing.Imaging;
using System.Drawing;

namespace SerialBrowserBridge.WebServer.Handler
{
    public class BarcodeHandler: IWebHandler
    {
        public void Initialize(WebServerCore webServer)
        {
        }

        public object Process(Request request, Response response)
        {
            if (!request.URL.StartsWith("/.barcode"))
                return HandleAction.False;

            var code = request.HasParameter(".code") ? request.Parameters[".code"] : String.Empty;
            var type = request.HasParameter(".type") ? request.Parameters[".type"] : "Code128";
            var size = request.HasParameter(".size") ? int.Parse(request.Parameters[".size"]) : 22;

            response.MimeType = "image/png";
            try
            {
                var draw = BarcodeDrawFactory.GetSymbology((BarcodeSymbology)Enum.Parse(typeof(BarcodeSymbology), type));
                var image = draw.Draw(code, size);
                image.Save(response.Content, ImageFormat.Png);

            }
            catch (Exception)
            {
                var image = new Bitmap(100, 50);
                Graphics.FromImage(image).DrawString("<Fehler>", new Font("Arial", 11), Brushes.Black, new Point(0, 0));
                image.Save(response.Content, ImageFormat.Png);
            }
            response.Content.Flush();

            return HandleAction.True;
        }

        public int Priority
        {
            get { return 100; }
        }
    }
}
